import SwiftUI
import MapKit

struct SelectMapPointView: UIViewRepresentable {
    @State var region: MKCoordinateRegion
    @Binding var selectCoordinate: CLLocationCoordinate2D
    var selectType: String = "start"
    var onSelect:(_ coord : CLLocationCoordinate2D ) -> Void  // 选择完成的回调
    
    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.showsUserLocation = true
        mapView.delegate = context.coordinator
        mapView.setRegion(region, animated: false)
        return mapView
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {
        // 如果外部修改了 centerCoordinate，更新地图显示
        if !uiView.centerCoordinate.isApproximatelyEqual(to: selectCoordinate) {
            uiView.setCenter(selectCoordinate, animated: true)
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: SelectMapPointView
        var currentAnnotation: MKPointAnnotation?
        
        init(_ parent: SelectMapPointView) {
            self.parent = parent
            super.init()
        }
        
        func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
            // 更新坐标为地图中心
            parent.selectCoordinate = mapView.centerCoordinate
            parent.region = mapView.region
            
            parent.onSelect(parent.selectCoordinate)
            
            // 更新标记位置
            updateAnnotation(for: mapView)
        }
        
        private func updateAnnotation(for mapView: MKMapView) {
            // 移除旧标记
            if let annotation = currentAnnotation {
                mapView.removeAnnotation(annotation)
            }
            
            // 创建新标记
            let annotation = MKPointAnnotation()
            annotation.coordinate = parent.selectCoordinate
            annotation.title = parent.selectType == "start" ? "S" : "E"
            
            // 添加到地图
            mapView.addAnnotation(annotation)
            currentAnnotation = annotation
        }
    }
}

extension CLLocationCoordinate2D {
    func isApproximatelyEqual(to other: CLLocationCoordinate2D, accuracy: Double = 1e-6) -> Bool {
        return abs(latitude - other.latitude) < accuracy &&
               abs(longitude - other.longitude) < accuracy
    }
}
